package com.hbnu.tonghengchang;

import java.io.*;
import java.net.*;

public class FileServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("文件服务器启动...");

        while (true) {
            Socket socket = serverSocket.accept();
            handleClient(socket);
        }
    }

    private static void handleClient(Socket socket) {
        try (DataInputStream dis = new DataInputStream(socket.getInputStream())) {
            String fileName = dis.readUTF();
            long fileSize = dis.readLong();

            try (FileOutputStream fos = new FileOutputStream("server_" + fileName)) {
                byte[] buffer = new byte[4096];
                int read;
                long remaining = fileSize;

                while (remaining > 0 && (read = dis.read(buffer, 0, (int)Math.min(buffer.length, remaining))) != -1) {
                    fos.write(buffer, 0, read);
                    remaining -= read;
                }
            }
            System.out.println("文件接收完成: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
